package com.fhc.view.dialog

import android.R.id.message
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.EmojiPeople
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.QuestionMark
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.fhc.view.R
import com.maxkeppeker.sheets.core.models.base.ButtonStyle
import com.maxkeppeker.sheets.core.models.base.IconSource
import com.maxkeppeker.sheets.core.models.base.SelectionButton
import com.maxkeppeker.sheets.core.models.base.UseCaseState
import com.maxkeppeker.sheets.core.models.base.rememberUseCaseState
import com.maxkeppeler.sheets.info.InfoDialog
import com.maxkeppeler.sheets.info.models.InfoBody
import com.maxkeppeler.sheets.info.models.InfoSelection
import com.maxkeppeler.sheets.input.InputDialog
import com.maxkeppeler.sheets.input.models.InputDivider
import com.maxkeppeler.sheets.input.models.InputHeader
import com.maxkeppeler.sheets.input.models.InputRadioButtonGroup
import com.maxkeppeler.sheets.input.models.InputSelection
import com.maxkeppeler.sheets.input.models.InputText
import com.maxkeppeler.sheets.input.models.InputTextField
import com.maxkeppeler.sheets.input.models.ValidationResult

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun FhcConfirmDialog( @DrawableRes appIcon:Int = R.drawable.github,
                      title:String = "Title",
                      message:String = "Message",
                      onPositiveClick: (() -> Unit)? = null,
                      onNegativeClick: (() -> Unit)? = null,
                      positiveButtonTxt:String = stringResource(R.string.text_confirm).uppercase(),
                      negativeButtonTxt:String = stringResource(R.string.text_cancel).uppercase(),
                      selection: InfoSelection = InfoSelection(
                          onPositiveClick = onPositiveClick,
                          onNegativeClick = onNegativeClick,
                          positiveButton =  SelectionButton(
                              text = positiveButtonTxt ,
                              type = ButtonStyle.ELEVATED
                          ),
                          negativeButton =  SelectionButton(
                              annotatedString = AnnotatedString.Builder().apply {
                                  withStyle(style = SpanStyle(color = Color.DarkGray)) {
                                      append(negativeButtonTxt)
                                  }
                              }.toAnnotatedString(),
                              type = ButtonStyle.ELEVATED,
                          )
                      )){

    val state = rememberUseCaseState(visible = true, onFinishedRequest =  {
        this.show()
    },onDismissRequest={
        onNegativeClick?.invoke()
    })
    InfoDialog(
        state = state,
        properties = DialogProperties(
            dismissOnBackPress=true,
            dismissOnClickOutside=false,
            usePlatformDefaultWidth=true,
        ),
        body = InfoBody.Custom{
            Column{
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .padding(0.dp),
                    horizontalArrangement = Arrangement.SpaceBetween, // 水平两端对齐
                    verticalAlignment = Alignment.CenterVertically    ){
                    Row(verticalAlignment = Alignment.CenterVertically ) {
                        Box(
                            modifier = Modifier
                                .size(50.dp) // 固定正方形尺寸
                                .background(
                                    color = Color.LightGray.copy(alpha = 0.1f), // 可选背景色
                                    shape = RoundedCornerShape(12.dp) // 圆角矩形
                                )
                                .clip(RoundedCornerShape(12.dp)) ){
                            Icon(
                                painter = painterResource(id = appIcon), // 加载应用图标R.mipmap.ic_launcher
                                contentDescription = null,
                                modifier = Modifier
                                    .size(50.dp)
                                    .padding(4.dp),
                                tint = Color.Unspecified // 保留图标原始颜色
                            )
                        }
                        Text( modifier = Modifier.padding(start = 10.dp),text = title.uppercase(),style = TextStyle(
                            fontSize = 18.sp,
                            fontFamily = FontFamily.SansSerif,
                            fontWeight = FontWeight.Bold
                        ) )
                    }

                    Box(
                        modifier = Modifier
                            .size(30.dp) // 设置背景大小
                            .background(
                                color = Color.LightGray, // 背景颜色
                                shape = CircleShape // 圆形背景
                            ),
                        contentAlignment = Alignment.Center // 图标居中
                    ) {
                        Icon(
                            imageVector = Icons.Filled.QuestionMark,
                            tint = Color.Red,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp) // 调整图标大小
                        )
                    }
                }
                Row( modifier = Modifier.padding(start = 60.dp),verticalAlignment = Alignment.CenterVertically ) {
                    Text(
                        message, style = TextStyle(
                            fontSize = 16.sp,
                            fontFamily = FontFamily.SansSerif,
                            fontWeight = FontWeight.Normal
                        )
                    )
                }
            }
        },
        selection = selection
    )

}

@Preview(showBackground = true)
@Composable
fun  SimpleInput( title:String = "Title", message:String = "Message", editValue:String = ""){
    var editVal by remember {mutableStateOf(editValue)}
    Column{
        Row(modifier = Modifier
            .fillMaxWidth()
            .padding(0.dp),
            horizontalArrangement = Arrangement.SpaceBetween, // 水平两端对齐
            verticalAlignment = Alignment.CenterVertically    ){
            Row(verticalAlignment = Alignment.CenterVertically ) {
                Box(
                    modifier = Modifier
                        .size(50.dp) // 固定正方形尺寸
                        .background(
                            color = Color.LightGray.copy(alpha = 0.1f), // 可选背景色
                            shape = RoundedCornerShape(12.dp) // 圆角矩形
                        )
                        .clip(RoundedCornerShape(12.dp)) ){
                    Icon(
                        painter = painterResource(id = R.drawable.github), // 加载应用图标R.mipmap.ic_launcher
                        contentDescription = null,
                        modifier = Modifier
                            .size(50.dp)
                            .padding(4.dp),
                        tint = Color.Unspecified // 保留图标原始颜色
                    )
                }
                Text( modifier = Modifier.padding(start = 10.dp),text = title.uppercase(),style = TextStyle(
                    fontSize = 18.sp,
                    fontFamily = FontFamily.SansSerif,
                    fontWeight = FontWeight.Bold
                ) )
            }
        }
        Row( modifier = Modifier.padding(start = 60.dp),verticalAlignment = Alignment.CenterVertically ) {
            Text(
                message, style = TextStyle(
                    fontSize = 16.sp,
                    fontFamily = FontFamily.SansSerif,
                    fontWeight = FontWeight.Normal
                )
            )
        }
        Row( modifier = Modifier.padding(start = 60.dp, top = 10.dp),verticalAlignment = Alignment.CenterVertically ) {
            val borderColor = colorResource(id = android.R.color.darker_gray)
            val errorColor = colorScheme.error
            var isError by remember { mutableStateOf(false) }
            isError = !editVal.matches(Regex("^[a-zA-Z0-9]{6,12}$"))
            val errorMessage = "请输入6-12位字母或数字"
            OutlinedTextField(
                value = editVal,
                onValueChange = {
                    editVal = it.take(10)
                    isError = !editVal.matches(Regex("^[a-zA-Z0-9]{6,12}$"))
                },
                label = {
                    Text("用户名", color = if (isError) errorColor else borderColor,)
                },
                isError = isError,
                supportingText = {
                    if (isError) {
                        Text(text = errorMessage, color = MaterialTheme.colorScheme.error)
                    }
                },
                trailingIcon = {
                    if (isError) {
                        Icon(
                            Icons.Filled.Error,
                            "error",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }
                },
                singleLine = true,
                modifier = Modifier.fillMaxWidth(),
                shape = MaterialTheme.shapes.medium,
                colors = OutlinedTextFieldDefaults.colors(
                    unfocusedContainerColor = Color.Transparent,
                    focusedContainerColor = Color.Transparent,
                    errorContainerColor = Color.Transparent,
                    focusedBorderColor = if (isError) errorColor else borderColor,
                    unfocusedBorderColor = if (isError) errorColor else borderColor,
                    errorBorderColor = errorColor,
                    disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                    cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                )
            )
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun FhcSimpleInputDialog(
    body: @Composable (() -> Unit)={},
    onPositiveClick: (() -> Boolean)? = null,
    onNegativeClick: (() -> Unit)? = null,
    positiveButtonTxt:String,
    negativeButton:String){
    var isActionDone = true
   val state = rememberUseCaseState(visible = true, onFinishedRequest =  {
           if(!isActionDone)  {
               this.show()
           }else{
               this.hide()
           }
       })
    InfoDialog(
        state = state,
        properties = DialogProperties(
            dismissOnBackPress=true,
            dismissOnClickOutside=false,
            usePlatformDefaultWidth=true,
        ),
        body = InfoBody.Custom{
            body()
        },
        selection = InfoSelection(
            onPositiveClick = {
                if(onPositiveClick != null){
                    isActionDone = onPositiveClick()
                }
                if(isActionDone)  {
                    state.hide()
                }
            },
            onNegativeClick = onNegativeClick,
            positiveButton =  SelectionButton(
                text = stringResource(R.string.text_confirm).uppercase() ,
                type = ButtonStyle.ELEVATED
            ),
            negativeButton =  SelectionButton(
                annotatedString = AnnotatedString.Builder().apply {
                    withStyle(style = SpanStyle(color = Color.DarkGray)) {
                        append(stringResource(R.string.text_cancel).uppercase())
                    }
                }.toAnnotatedString(),
                type = ButtonStyle.ELEVATED,
            )
        )
    )

}


